package com.xinyuan.trade.Utils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.xinyuan.trade.Activity.BaseActivity;

/**
 * 工具类
 * 
 * @author daiy
 * 
 */
public class Utils {

	/**
	 * 清空ImageLoader内存缓存
	 */
	public static void clearMemoryCacheImageLoader() {
		ImageLoader.getInstance().clearMemoryCache();
	}

	/**
	 * 清空ImageLoader存储卡缓存
	 */
	public static void clearDiscCacheImageLoader() {
		ImageLoader.getInstance().clearDiscCache();
	}

	/**
	 * 隐藏输入框
	 * 
	 * @param self
	 * @param v
	 */
	public static void hiddenInput(BaseActivity self, View v) {
		InputMethodManager imm = (InputMethodManager) self
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
	}

	/**
	 * 获得文件夹大小
	 * 
	 * @param dir
	 * @return
	 */
	private static long getFolderSize(File dir) {
		if (dir.exists()) {
			long result = 0;
			File[] fileList = dir.listFiles();
			for (int i = 0; i < fileList.length; i++) {
				// Recursive call if it's a directory
				if (fileList[i].isDirectory()) {
					result += getFolderSize(fileList[i]);
				} else {
					// Sum the file size in bytes
					result += fileList[i].length();
				}
			}
			return result; // return the file size
		}
		return 0;
	}

	/**
	 * 清理缓存
	 * 
	 * @param file
	 *            要删除的根目录
	 */
	public static void clearFolder(File file) {
		if (file.exists() == false) {
			return;
		} else {
			if (file.isFile()) {
				file.delete();
				return;
			}
			if (file.isDirectory()) {
				File[] childFile = file.listFiles();
				// if (childFile == null || childFile.length == 0) {
				// file.delete();
				// return;
				// }
				for (File f : childFile) {
					clearFolder(f);
				}
				file.delete();
			}
		}
	}

	/**
	 * 获取文件夹大小
	 * 
	 * @param path
	 * @return
	 */
	public static String dirSize(String path) {
		File dir = new File(path);

		if (dir.exists()) {
			long bytes = getFolderSize(dir);
			if (bytes < 1024)
				return bytes + " B";
			int exp = (int) (Math.log(bytes) / Math.log(1024));
			String pre = ("KMGTPE").charAt(exp - 1) + "";

			return String.format("%.1f %sB", bytes / Math.pow(1024, exp), pre);
		}

		return "0";
	}

	/**
	 * 是否存在SD卡
	 * 
	 * @return
	 */
	public static boolean hasSdcard() {
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			return true;
		} else
			return false;
	}

	/**
	 * 获取软件版本号
	 * 
	 * @param context
	 * @return
	 */
	public static String getVersion(Context context) {
		String version = "";
		try {
			version = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0).versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return version;
	}

	/**
	 * 获取网络连接状态
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isNetworkConnected(Context context) {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mNetworkInfo = mConnectivityManager
					.getActiveNetworkInfo();
			if (mNetworkInfo != null) {
				return mNetworkInfo.isAvailable();
			}
		}
		return false;
	}

	public static String getNowTime() {
		return new SimpleDateFormat("MM-dd HH:mm", Locale.CHINA)
				.format(new Date());
	}

	/**
	 * 日期格式化
	 * 
	 * @param ptime
	 * @return
	 */
	public static String formatDataByDay(int ptime) {
		try {
			Date date = new Date(ptime * 1000L);
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			return formatter.format(date);
		} catch (Exception e) {
			return "";
		}
	}

	/** 
	 * ScrollView中嵌套ListView时显示不全
	 * @param listView
	 */
	public static void setListViewHeightBasedOnChildren(ListView listView) {
		// 获取ListView对应的Adapter
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			// pre-condition
			return;
		}

		int totalHeight = 0;
		for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回数据项的数目
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0); // 计算子项View 的宽高
			totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		// listView.getDividerHeight()获取子项间分隔符占用的高度
		// params.height最后得到整个ListView完整显示需要的高度
		listView.setLayoutParams(params);
	}
}
